
package ru.surfstudio.webservicetemplate.parser;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import ru.surfstudio.webservicetemplate.dto.GoogleSearchResultDto;
import ru.surfstudio.webservicetemplate.exception.AuthenticationException;
import ru.surfstudio.webservicetemplate.exception.TransportException;

public class GoogleSearchParser implements Parser<ArrayList<GoogleSearchResultDto>> {

    public ArrayList<GoogleSearchResultDto> parse(String responseString) throws AuthenticationException,
            TransportException {
        try {
            ArrayList<GoogleSearchResultDto> resultList = new ArrayList<GoogleSearchResultDto>();
            JSONObject response = new JSONObject(responseString);
            JSONObject responseData = response.getJSONObject("responseData");
            JSONArray results = responseData.getJSONArray("results");
            for (int i = 0; i < results.length(); i++) {
                JSONObject json = results.getJSONObject(i);
                GoogleSearchResultDto dto = new GoogleSearchResultDto();
                dto.content = json.getString("content");
                dto.title = json.getString("title");
                dto.url = json.getString("url");
                resultList.add(dto);
            }
            return resultList;
        } catch (Exception e) {
            throw new TransportException("GoogleSearchParser exception", e);
        }
    }
}
